package cc.admin.modules.quartz.job;

import cc.admin.common.constant.CommonConstant;
import cc.admin.common.exception.CcAdminException;
import cc.admin.common.sys.util.JwtUtil;
import cc.admin.common.util.RedisUtil;
import cc.admin.common.util.SpringContextUtils;
import cc.admin.modules.shiro.authc.JwtToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;
/**
 * 做一个抽象job 把虚拟用户信息包起来
 * @author: ZhangHouYing
 * @date: 2023-09-18 16:05
 */
public abstract class AbstractJob implements Job {

	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		String group = jobExecutionContext.getJobDetail().getKey().getGroup();
		JdbcTemplate jdbcTemplate = (JdbcTemplate) SpringContextUtils.getBean("jdbcTemplate");
		List<Map<String, Object>> userList = jdbcTemplate.queryForList("select username from sys_user where is_admin='1' and tenant_id=?", group);
		if(userList.size()>0){
			Map<String, Object> user = userList.get(0);
			String userName = (String)user.get("username");
			String token = JwtUtil.sign(userName, "123456");
			DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SpringContextUtils.getBean("securityManager");
			SecurityUtils.setSecurityManager(securityManager);
			RedisUtil redisUtil = (RedisUtil) SpringContextUtils.getBean("redisUtil");
			JwtToken jwtToken = new JwtToken(token);
			redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
			// 这里以系统管理员身份运行任务
			SecurityUtils.getSubject().login(jwtToken);
			this.doExecute(jobExecutionContext);
		} else {
			CcAdminException.runTimeException("当前任务没有可用的系统管理员，公司编号:"+group);
		}

	}

	/**
	 * 实际执行的
	 * @param jobExecutionContext
	 * @throws JobExecutionException
	 */
	public abstract void doExecute(JobExecutionContext jobExecutionContext) throws JobExecutionException;
}
